package codingforgreat.class08;

import java.util.LinkedList;

public class Class01_ExpressionCompute {

    public static int calculate(String str) {
        return f(str.toCharArray(), 0)[0];
    }

    //int[0] = res int[1] = index
    public static int[] f(char[] str, int i){
        LinkedList<String> linkedList = new LinkedList<>();
        int cur = 0;
        int[] bra = null;
        while (i < str.length && str[i] != ')') {
            if(str[i] - '0' >= 0 && str[i] - '0' <= 9){
                cur = cur* 10 + (str[i++] - '0');
            }else if(str[i] == '('){
                 bra = f(str,i + 1);
                cur = bra[0];
                i = bra[1] + 1;
            }else{
                addNum(linkedList, cur, str[i++]);
                cur = 0;
            }
        }
        addNum(linkedList, cur, '+');
        return new int[] { getAns(linkedList), i };
    }
    public static void  addNum(LinkedList<String> queue, int cur, char op){
        if(!queue.isEmpty() && (queue.peekLast().equals("*") || queue.peekLast().equals("/"))){
            String top = queue.pollLast();
            int pre = Integer.parseInt(queue.pollLast());
            cur = top.equals("*") ? pre * cur : pre / cur;
        }
        queue.addLast(String.valueOf(cur));
        queue.addLast(String.valueOf(op));
    }
    public static int getAns(LinkedList<String> queue){
        int ans = Integer.parseInt(queue.pollFirst());
        while (queue.size() > 1){
            String op = queue.pollFirst();
            int num = Integer.valueOf(queue.pollFirst());
            ans += op.equals("+") ? num : -num;
        }
        return ans;
    }

    public static void main(String[] args) {
        String s = "3*(2-1)+(5*(6+1))";
        System.out.println(calculate(s));
    }


}
